package com.lk;

/**
 * 1.修饰方法
 *
 * 2.修饰代码块
 *   只有当前对象需要公用这把锁
 * 3.修饰对象
 *   调用对象时，公用一把锁
 *   (调用基本类型的分装类，使用++操作时，因为++操作会得到新的对象，所以锁会失效)
 * 5.修饰静态方法
 *  所有的对象公用这把锁
 * 6.修饰class
 *   所有对象公用这把锁
 * */
public class TestSynchronized {
    public static void main(String[] args) {
        DemoSynCode demoSynCode = new DemoSynCode();
        DemoSynCode demoSynCode1 = new DemoSynCode();
        new Thread(demoSynCode,"thread1").start();
        new Thread(demoSynCode,"thread2").start();
    }

}

class DemoSynCode implements Runnable{

    Integer count = 0;

    DemoCount demoCount = new DemoCount(1,"sss");

    @Override
    public void run() {
        synchronized (count){
            for(int i=0; i<10; i++){
//                demoCount.setId(demoCount.getId()+1);
//                System.out.println(Thread.currentThread().getName()+" count:"+(demoCount.getId()) );
                System.out.println(Thread.currentThread().getName()+" count:"+(++count) );
                try {
                    Thread.sleep(400);
                } catch (InterruptedException e) {
                }
//                System.out.println(Thread.currentThread().getName()+" count:"+i );
            }
        }
    }
}

class DemoCount{
    private int id;
    private String name;

    public DemoCount(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}